package com.app.util;

import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

public class ReceiptGenerator {

    @Value("${systemFont}")
    private static String systemFont;


    public static void main(String[] args) throws Exception {
        ReceiptGenerator receiptGenerator = new ReceiptGenerator();
        receiptGenerator.systemFont = "C:\\Windows\\Fonts\\simsun.ttc,0";

        String tenantName = "马杰";
        String leaseCertificateNumber = "1234567890";
        LocalDateTime paymentStartTime = LocalDateTime.of(2021, 1, 1, 0, 0, 0);
        LocalDateTime paymentEndTime = LocalDateTime.of(2021, 12, 31, 0, 0, 0);
        BigDecimal payableAmount = new BigDecimal("123456.00");
        BigDecimal governmentSubsidies = new BigDecimal("987654.00");
        BigDecimal actualAmount = new BigDecimal("741852.00");
        BigDecimal lateAmount = new BigDecimal("66.00");
        Double usableArea = 100.0;
        BigDecimal chargeStandard = new BigDecimal("120.00");
        BigDecimal chargeUnitPriceSubsidy = new BigDecimal("100.00");
        BigDecimal actualStandard = new BigDecimal("112.00");
        String addressStr = "甘肃省酒泉市肃州区铁人路12号";

        String receipt_number = receiptGenerator.generateReceipt(tenantName, leaseCertificateNumber, paymentStartTime, paymentEndTime,
                payableAmount, governmentSubsidies, actualAmount, lateAmount, usableArea, chargeStandard, chargeUnitPriceSubsidy, actualStandard,
                addressStr);

        System.err.println("receipt_number: " + receipt_number);
    }

    public static String generateReceipt(String tenantName, String leaseCertificateNumber, LocalDateTime paymentStartTime, LocalDateTime paymentEndTime,
                                  BigDecimal payableAmount, BigDecimal governmentSubsidies, BigDecimal actualAmount, BigDecimal lateAmount,
                                  Double usableArea, BigDecimal chargeStandard, BigDecimal chargeUnitPriceSubsidy, BigDecimal actualStandard,
                                  String addressStr) {

        String receipt_number = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + ThreadLocalRandom.current().nextInt(100, 1000);

        String filePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + receipt_number + ".pdf";
        Document document = new Document();
        try {

            // 检查目录是否存在，如果不存在则创建
            File directory = new File(System.getProperty("user.dir") + File.separator + "file");
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    throw new IOException("无法创建目录: " + directory.getAbsolutePath());
                }
            }

            PdfWriter.getInstance(document, new FileOutputStream(filePath));
            document.open();

            // 设置字体，字号加大两号，原来12号，现在设为14号
            BaseFont baseFont = BaseFont.createFont(systemFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font normalFont = new Font(baseFont, 14);
            Font boldFont = new Font(baseFont, 14, Font.BOLD);

            // 姓名及编号
            addStyledText(tenantName + "(" + leaseCertificateNumber + ")", normalFont, document, false);

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
            // 格式化日期
            String formattedDate = currentDate.format(formatter);
            // 日期和编号
            addStyledText(formattedDate + "\n" + receipt_number, normalFont, document, true);

            // 将LocalDateTime格式化为yyyy-MM
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String formattedStartTime = paymentStartTime.format(dateTimeFormatter);
            String formattedEndTime = paymentEndTime.format(dateTimeFormatter);

            // 交租时间
            addStyledText("交租时间：   " + formattedStartTime + " 至 " + formattedEndTime, normalFont, document, false);

            // 应交租金
//            addStyledText("应交租金：         " + payableAmount.toString(), normalFont, document, false);

            // 政府补贴
//            addStyledText("政府补贴：         " + governmentSubsidies.toString(), normalFont, document, false);

            // 实交租金
            addStyledText("实交租金：         " + actualAmount.toString(), normalFont, document, false);

            // 滞纳金
//            addStyledText("滞 纳 金：         " + lateAmount.toString(), normalFont, document, false);

            // 使用面积
//            addStyledText("使用面积：         " + usableArea + "㎡", normalFont, document, false);

            // 租金标准
            addStyledText("租金标准：         " + chargeStandard + "/㎡", normalFont, document, false);

            // 政府补贴（每平米）
//            addStyledText("政府补贴：         " + chargeUnitPriceSubsidy + "/㎡", normalFont, document, false);

            // 实收标准
//            addStyledText("实收标准：         " + actualStandard + "/㎡", normalFont, document, false);

            // 大写金额，居中显示
            String capitalAmountStr = AmountConverter.convertToChinese(actualAmount);
            addStyledText(capitalAmountStr, boldFont, document, Element.ALIGN_CENTER);

            // 金额
            addStyledText(actualAmount.toString() + "元", normalFont, document, true);

            // 地址，居中显示
            addStyledText(addressStr, normalFont, document, Element.ALIGN_CENTER);

            document.close();
            System.out.println("PDF 收据已生成：" + filePath);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
        return receipt_number;
    }

    private static void addStyledText(String text, Font font, Document document, int alignment) throws DocumentException {
        Chunk chunk = new Chunk(text, font);
        Paragraph paragraph = new Paragraph();
        paragraph.add(chunk);
        paragraph.setAlignment(alignment);
        document.add(paragraph);
    }

    private static void addStyledText(String text, Font font, Document document, boolean isRightAligned) throws DocumentException {
        int alignment = isRightAligned? Element.ALIGN_RIGHT : Element.ALIGN_LEFT;
        addStyledText(text, font, document, alignment);
    }
}